import requests
from lxml import etree
import os
class MeiTu():
    def __init__(self):
        self.url='https://www.mzitu.com/'
        self.headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3770.100 Safari/537.36",
            "Referer": "https://www.mzitu.com/"
        }
        self.pt=input('请填写你想保存的文件夹名字(默认位置:img_down)：')

    def get_url(self,url):
        return requests.get(url=url,headers=self.headers,timeout=5).content

    def get_urllist(self,html):
        lazys=html.xpath('//img[@class="lazy"]')
        url_list=[]
        for lazy in lazys:
            item={}
            item['url'] = lazy.xpath('../@href')[0]
            item['name'] = lazy.xpath('./@alt')[0]
            url_list.append(item)
        url_page=html.xpath('//div[@class="nav-links"]//a[@class="next page-numbers"]/@href')
        return url_list,url_page

    def get_img(self,url):
        img_list=[]
        while True:
            res = self.get_url(url).decode()
            html=etree.HTML(res)
            jpgs=html.xpath('//img[@class="blur"]/@src')
            # print(jpgs)
            for i in jpgs:
                img_list.append(i)
            page=html.xpath('//span[contains(text(),"下一页")]/../@href')
            if page:
                url=page[0]
            else:
                break
        return img_list


    def make_dir(self,path):
        if os.path.exists(path):
            pass
        else:
            os.mkdir(path)


    def save_img(self,url,path):
        if len(self.pt)>=1:
            pt=os.getcwd()+'/%s'%self.pt
            self.make_dir(pt)
        else :
            pt = os.getcwd() + '/img_down'
            self.make_dir(pt)
        paths = pt+'/[%sP]%s/' % (len(url), path)
        print('开始下载%s套图，共计：%s张'%(path,len(url)))
        self.make_dir(paths)
        for i in url:
            print('*'*10,i+'*'*10+'[下载完成]')
            content=self.get_url(i)
            jpgname =paths+i[-9:]
            with open(jpgname,'wb') as f:
                f.write(content)
                f.close()

    def run(self):
        while True:
            try :
                res=self.get_url(self.url)
                html=etree.HTML(res)
                url_list,url_page=self.get_urllist(html)
                for i in url_list:
                    img_list=self.get_img(i['url'])
                    self.save_img(img_list,i['name'])
                if url_list:
                    self.url = url_page[0]
                else:
                    break
            except BaseException as e:
                continue

def main():
    meitu = MeiTu()
    meitu.run()

if __name__ == '__main__':
    main()